#include <vector>
#include <set>
#include <iostream>
#include <unordered_map>
#include <numeric>

using namespace std;

vector<int> spiralOrder(vector<vector<int>>& matrix) {
    vector<int> ret = { }; int i = 0, j = 0;
    while(ret.size() != matrix[0].size() * matrix.size()){
        while(i >= 0 && i < matrix.size() && j >= 0 && j < matrix[0].size() && matrix[i][j] != INT_MIN ){
            ret.push_back(matrix[i][j]);
            matrix[i][j++] = INT_MIN;
        }
        i++; j--;
        while(i >= 0 && i < matrix.size() && j >= 0 && j < matrix[0].size() && matrix[i][j] != INT_MIN ){
            ret.push_back(matrix[i][j]);
            matrix[i++][j] = INT_MIN;
        }
        i--; j--;
        while(i >= 0 && i < matrix.size() && j >= 0 && j < matrix[0].size() && matrix[i][j] != INT_MIN ){
            ret.push_back(matrix[i][j]);
            matrix[i][j--] = INT_MIN;
        }
        i--; j++;
        while(i >= 0 && i < matrix.size() && j >= 0 && j < matrix[0].size() && matrix[i][j] != INT_MIN ){
            ret.push_back(matrix[i][j]);
            matrix[i--][j] = INT_MIN;
        }
        i++; j++;
    }
    return ret;
}

int main(){
    vector<vector<int>> nums = { {1,2,3},{4,5,6},{7,8,9} };
    vector<int> ret = spiralOrder(nums);
    for(int i = 0; i < ret.size(); i++){
        cout << ret[i] << endl;
    }
    return 0;
}